'use client'
/**
 * @author shaosong
 * @description
 */
import React from 'react'
import { Card, CardBody } from '@nextui-org/react'

type ColumnProps = { name: string; uid: string }

export class MobileTableProps {
  columns?: ColumnProps[]
  items?: any[]
  renderCell?: (
    item: any,
    columnKey: React.Key
  ) => string | number | React.JSX.Element
}

const MobileTable: React.FC<MobileTableProps> = ({
  columns,
  items,
  renderCell
}) => {
  const columnsDom = React.useCallback(
    (item: any, index: string): JSX.Element[] | JSX.Element => {
      if (columns?.length) {
        return (
          <li key={index} className="mt-4">
            <Card className="hover:bg-[#F7F7F7]">
              <CardBody>
                {columns?.map((column, key) => (
                  <div key={`${index}-${key}`} className="flex justify-between">
                    <div>{column.name}:</div>
                    <div className="max-w-[80%] overflow-hidden whitespace-nowrap text-ellipsis">
                      {renderCell
                        ? renderCell?.(item, column.uid as string)
                        : item?.[column.uid]}
                    </div>
                  </div>
                ))}
              </CardBody>
            </Card>
          </li>
        )
      } else {
        return <li key={index}>''</li>
      }
    },
    [columns, renderCell]
  )

  return React.useMemo(
    () => (
      <div className="w-full">
        <ul aria-label="Actions">
          {items?.map((item, index) => columnsDom(item, String(index))) as any}
        </ul>
      </div>
    ),
    [items, columns]
  )
}

export default MobileTable
